package com.teach.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImgServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int width= 139;      //设置宽高
		int height=48;
		
		Random r = new Random(); 
		String code = ""+r.nextInt(10)+r.nextInt(10)+r.nextInt(10)+r.nextInt(10);//随机数字
		
		BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics g=img.getGraphics();
		
		g.setColor(new Color(255,255,255));  //设置白色背景
		g.fillRect(0, 0, width, height); 
		
		for(int i=0;i<height/2;i++){ 
			g.setColor(new Color(150+r.nextInt(100),150+r.nextInt(100),150+r.nextInt(100) ));     //随机生成颜色
			g.drawLine(0, r.nextInt(height), width, r.nextInt(height));     //设置多种颜色干扰线
		}
		
		//绘制文字
		int fontSize=36; 
		g.setFont(new Font("微软雅黑", Font.BOLD, fontSize)); 
		int w = width/code.length(); 
		for(int i=0;i<code.length();i++){
			g.setColor(new Color(50+r.nextInt(150),50+r.nextInt(150),50+r.nextInt(150))); //随机颜色 50-200 
			g.drawString(code.substring(i,i+1), i*w, height- r.nextInt(height-fontSize)); 
			}
		response.reset();
		response.setContentType("image/jpeg");
		ImageIO.write(img, "jpg", response.getOutputStream()); 
		response.flushBuffer(); 
		
		
	}
}
